<?php

declare(strict_types=1);

namespace Jooau\Base\Middleware;

use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Model\Permission;
use Donjan\Permission\Exceptions\UnauthorizedException;

class PermissionMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {

        //去掉路由参数
        $dispatcher = $request->getAttribute('Hyperf\HttpServer\Router\Dispatched');
        $route = $dispatcher->handler->route;
        $path = '/' . config("app_name") . $route . '/' . $request->getMethod();
        $path = strtolower($path);
        $permission = Permission::getPermissions(['name' => $path])->first();
        $admin_user = $request->getAttribute('admin_user');
        if ($admin_user && (!$permission || ($permission && $admin_user->checkPermissionTo($permission, 'manager')))) {
            return $handler->handle($request);
        }
        throw new UnauthorizedException('无权进行该操作', 403);

    }
}